#!/bin/bash

echo $0
set -e
set -x

debian_mirror=$1

printf 'APT::Install-Recommends "0";\nAPT::Install-Suggests "0";\n' \
       > /etc/apt/apt.conf.d/99no-install-recommends

printf 'APT::Acquire::Retries "20";\n' \
       > /etc/apt/apt.conf.d/99acquire-retries

printf 'APT::Periodic::Update-Package-Lists "0";\nAPT::Periodic::Unattended-Upgrade "0";\n' \
       > /etc/apt/apt.conf.d/99no-auto-updates

if echo $debian_mirror | grep '^https' 2>&1 > /dev/null; then
    apt-get -y update
    apt-get -y install apt-transport-https
fi

sed -i "s,http://ftp.uk.debian.org/debian/,${debian_mirror},g" /etc/apt/sources.list

if grep --quiet jessie /etc/apt/sources.list; then
    echo "deb $debian_mirror jessie-backports main" > /etc/apt/sources.list.d/backports.list
    echo "deb $debian_mirror testing main" > /etc/apt/sources.list.d/testing.list
    printf "Package: *\nPin: release o=Debian,a=testing\nPin-Priority: -300\n" > /etc/apt/preferences.d/debian-testing
fi

dpkg --add-architecture i386

apt-get -y update
apt-get -y upgrade --download-only
apt-get -y upgrade

packages="
 ant
 asn1c
 ant-contrib
 autoconf
 autoconf2.13
 automake/testing
 automake1.11
 autopoint
 bison
 bzr
 ca-certificates-java/jessie-backports
 cmake/jessie-backports
 curl
 expect
 faketime
 flex
 gettext/jessie-backports
 gettext-base/jessie-backports
 git-core/jessie-backports
 git-svn/jessie-backports
 gperf
 graphviz
 imagemagick
 inkscape
 javacc
 libarchive-zip-perl
 libexpat1-dev
 libgcc1:i386
 libglib2.0-dev
 liblwp-protocol-https-perl
 liblzma-dev
 libncurses5:i386
 librsvg2-bin
 libsaxonb-java
 libssl-dev
 libstdc++6:i386
 libtool/testing
 libtool-bin/testing
 make
 maven
 mercurial/jessie-backports
 nasm
 nodejs
 openjdk-8-jre-headless
 openjdk-8-jdk-headless
 optipng
 p7zip
 pandoc
 perlmagick
 pkg-config
 python-gnupg
 python-lxml
 python-magic
 python-setuptools
 python3-git/jessie-backports
 python3-gitdb/jessie-backports
 python3-gnupg
 python3-pyasn1
 python3-pyasn1-modules
 python3-requests
 python3-smmap/jessie-backports
 python3-yaml
 python3-ruamel.yaml
 quilt
 realpath
 rsync
 scons
 sqlite3
 subversion
 swig
 texinfo
 transfig
 unzip
 vorbis-tools
 xsltproc
 yasm
 zip
 zlib1g:i386
"
apt-get install --yes $packages --download-only
apt-get install --yes $packages

highestjava=`update-java-alternatives --list | sort -n | tail -1 | cut -d ' ' -f 1`
update-java-alternatives --set $highestjava
